package main

import (
	"io"
	"log"
	"math/rand"
	"net/http"
	"os"
	"time"
)

const maxUploadSize = 1 * 1024 * 1024

// 生成32位MD5
//func generateMD5(text string) string{
//	ctx := md5.New()
//	ctx.Write([]byte(text))
//	return hex.EncodeToString(ctx.Sum(nil))
//}

// 生成随机字符串
func GetRandomString(length int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	hashfile := "/upload/" + "upload-" + GetRandomString(16) + ".json"

	//确认文件大小是否超过限制（1MB）
	//r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
	//if err := r.ParseMultipartForm(maxUploadSize); err != nil {
	//	w.WriteHeader(403)
	//	w.Header().Add("Code", "failed")
	//	_, err := w.Write([]byte("FILE_TOO_BIG. Nothing to do!"))
	//	if err != nil {
	//		log.Fatal(err)
	//	}
	//	return
	//}

	f, err := os.Create("./build" + hashfile)
	if err != nil {
		log.Fatal(err)
	}
	_, err = io.Copy(f, r.Body)
	if err != nil {
		log.Fatal(err)
	}
	err = f.Close()
	if err != nil {
		log.Fatal(err)
	}
	//w.Header().Add("path", hashfile)
	w.WriteHeader(200)
	w.Header().Add("Code", "success")
	//log.Println(w)
	_, err = w.Write([]byte("[{\"filename\":\"" + hashfile + "\"}]"))
	if err != nil {
		log.Fatal(err)
	}
}

func setupRoutes() {
	http.HandleFunc("/api/upload", uploadHandler)

	DocRoot := http.FileServer(http.Dir("./build"))

	http.Handle("/", http.StripPrefix("/", DocRoot))

	log.Println("Listening on :8080")
	http.ListenAndServe(":8080", nil)
}

func main() {
	//如果没有upload目录则创建
	_, err := os.Stat("build/upload")
	if os.IsNotExist(err) {
		os.Mkdir("build/upload", 0644)
	}

	//配置路由
	setupRoutes()
}
